<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card class="box-card">
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" @clear="getUserList" clearable>
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                    <el-button type="primary" @click="addUserDialogVisible = true">添加用户</el-button>
                </el-col>
            </el-row>
            <el-table
                :data="userList"
                border
                stripe
                style="width: 100%"
                :row-class-name="tableRowClassName">
                <!-- 索引列 -->
                <el-table-column type="index" label="序号" width="50"></el-table-column>
                <el-table-column prop="username" label="姓名" width="180"></el-table-column>
                <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
                <el-table-column prop="mobile" label="电话"></el-table-column>
                <el-table-column prop="role_name" label="角色"></el-table-column>
                <!-- 使用自定义插槽实现自定义样式 -->
                 <el-table-column prop="mg_state" label="状态">
                    <template slot-scope="scope">
                        <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
                    </template>
                </el-table-column>
                 <el-table-column label="操作">
                     <template slot-scope="scope">
                        <!-- 修改 -->
                        <el-button type="primary" icon="el-icon-edit" size="mini" circle @click="showEditUserDialog(scope.row.id)"></el-button>
                        <!-- 删除 -->
                        <el-button type="danger" icon="el-icon-delete" size="mini" circle @click="deleteUser(scope.row.id)"></el-button>
                        <!-- 分配权限 -->
                        <el-tooltip effect="dark" content="分配权限" placement="top" :enterable="false">
                            <el-button type="warning" icon="el-icon-setting" size="mini" circle></el-button>
                        </el-tooltip>  
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页组件 -->
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 5, 10, 20]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card> 
        <!-- 添加用户对话框 -->
        <el-dialog
            title="新增"
            :visible.sync="addUserDialogVisible"
            width="50%"
            center
            @close="onAddDialogDismss">
            <!-- 中间表单内容 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addForm" label-width="100px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addForm.username"></el-input>
                </el-form-item>
                 <el-form-item label="密码" prop="password">
                    <el-input v-model="addForm.password"></el-input>
                </el-form-item>
                 <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addForm.email"></el-input>
                </el-form-item>
                 <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="addForm.mobile"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 编辑 -->
        <el-dialog
            title="编辑"
            :visible.sync="editUserDialogVisible"
            @close="onEditDialogDismiss"
            width="50%"
            center>
            <!-- 中间表单内容 -->
            <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px">
                <el-form-item label="用户名">
                    <el-input v-model="editForm.username" disabled></el-input>
                </el-form-item>
                 <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editForm.email"></el-input>
                </el-form-item>
                 <el-form-item label="手机号" prop="mobile">
                    <el-input v-model="editForm.mobile"></el-input>
                </el-form-item>
            </el-form>    
            <span slot="footer" class="dialog-footer">
                <el-button @click="editUserDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="editUserInfo">确 定</el-button>
            </span>
        </el-dialog>
    </div>
   
</template>
<script>
import { getUsers,updateUserState,addUser,getUserInfo,updateUserInfo,deleteUser} from '../../config/api'
import { isEmail,isMobile } from '../../utils/validator'
export default {
    data(){
        var checkEmail = (rule,value,callback)=>{
            if(isEmail(value)){
                return callback()
            } 
            return callback(new Error("请输入合法邮箱"))
        }
        var checkMobile = (rule,value,callback)=>{
            if(isMobile(value)){
                return callback()
            } 
            return callback(new Error("请输入正确的手机号"))
        }
        return {
            queryInfo:{
                query:'',
                pagenum :1,
                pagesize:10
            },
            //接口数据
            userList:[],
            //总页数
            total:0,
            //添加用户弹框是否显示
            addUserDialogVisible:false,
            //编辑用户弹框是否显示
            editUserDialogVisible:false,
            //添加用户表单数据
            addForm:{
                username:'',
                password:'',
                email:'',
                mobile:''
            },
            //添加用户表单规则
            addFormRules:{
                username:[
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 3, max: 10, message: '长度在 3 到 10 个字符', trigger: 'blur' }
                ],
                password:[
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
                ],
                email:[
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            },
            //编辑时的用户信息
            editForm:{},
            //编辑表单验证规则
            editFormRules:{
                email:[
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { validator: checkEmail, trigger: 'blur' }
                ],
                mobile:[
                    { required: true, message: '请输入手机号码', trigger: 'blur' },
                    { validator: checkMobile, trigger: 'blur' }
                ]
            }
        }
    },
    created(){
      this.getUserList()
    },
    methods:{
        getUserList(){
            getUsers(this.queryInfo).then(res=>{
                this.userList = res.users;
                this.total = res.total;
            }).catch(e=>{
                this.$message.error("获取用户列表失败");
            });
        },
        //自定义表格行颜色背景
        tableRowClassName({row, rowIndex}) {
            if (rowIndex == 1) {
                return 'warning-row';
            } else if (rowIndex == 3) {
                return 'success-row';
            }
            return '';
        },
        //监听pageSize变化监听
        handleSizeChange(newSize) {
            this.queryInfo.pagesize = newSize;
            this.getUserList();
        },
        //监听pagenum变化监听
        handleCurrentChange(curPage) {
            this.queryInfo.pagenum = curPage;
            this.getUserList();
        },
        //用户状态发生改变
        userStateChange(userInfo){
            updateUserState(userInfo.id,userInfo.mg_state)
            .then(res=>{
                this.$message.success("更新用户状态成功");
            }).catch(e=>{
                userInfo.mg_state = !userInfo.mg_state;
                this.$message.error("更新用户状态失败");
            })
        },
        //添加用户的对话框消失事件
        onAddDialogDismss(){
            this.$refs.addForm.resetFields();
        },
        //添加用户的预校验
        addUser(){
            this.$refs.addForm.validate(valid => {
                if(!valid) return;
                //添加用户请求
                addUser(this.addForm)
                .then(res=>{
                    this.$message.success("添加用户成功");
                    this.addUserDialogVisible = false;
                    this.getUserList();
                }).catch(e=>{
                    this.$message.error("添加用户失败");
                })
            })
        },
        //显示编辑用户的弹框
        showEditUserDialog(uid){
            getUserInfo(uid).then(res=>{
                this.editForm = res;
            }).catch(e=>{

            })
            this.editUserDialogVisible = true;
        },
        onEditDialogDismiss(){
            this.$refs.editForm.resetFields();
        },
        //编辑用户信息预校验
        editUserInfo(){
            this.editUserDialogVisible = false;
            this.$refs.editForm.validate(valid=>{
                if(!valid) return
                updateUserInfo(this.editForm.id,this.editForm.email,this.editForm.mobile).then(res=>{
                    this.$message.success("更新用户数据成功")
                    this.getUserList();
                }).catch(e=>{
                    this.$message.success("更新用户数据失败")
                })
            })
        },
        //删除用户
        async deleteUser(uid){
           const result = await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(e=>e)
            console.log(result)
            if(result == 'confirm'){
                deleteUser(uid).then(res=>{
                    this.$message.success("删除用户成功")
                    this.getUserList();
                }).catch(e=>{
                    this.$message.error("删除用户失败")
                })
            }
        }
    }
    
}
</script>
<style lang="less" scoped>
.warning-row {
    background: oldlace;
}

.success-row {
    background: #f0f9eb;
}
</style>